package com.starry.module.system.core.file.service.impl;

import com.starry.core.common.execption.ServiceException;
import com.starry.module.system.api.file.enums.FileStorage;
import com.starry.module.system.core.file.client.AbstractFileClient;
import com.starry.module.system.core.file.client.FileClient;
import com.starry.module.system.core.file.client.local.LocalFileClient;
import com.starry.module.system.core.file.client.s3.S3FileClient;
import com.starry.module.system.core.file.entity.FileConfig;
import com.starry.module.system.core.file.service.FileClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 文件客户端工厂实现类
 *
 * @author xiaoke
 */
@Service
@Slf4j
public class FileClientFactoryImpl implements FileClientFactory {

    /**
     * 文件客户端 Map
     * key：配置编号
     */
    private final ConcurrentMap<Long, AbstractFileClient> clients = new ConcurrentHashMap<>();

    @Override
    public FileClient getFileClient(Long configId) {
        AbstractFileClient client = clients.get(configId);
        if (client == null) {
            log.error("[getFileClient][配置编号({}) 找不到客户端]", configId);
        }
        return client;
    }

    @Override
    public FileClient createOrUpdateFileClient(FileConfig config) {
        AbstractFileClient client = clients.get(config.getId());
        if (client == null) {
            client = createFileClient(config);
            client.init();
            clients.put(config.getId(), client);
        } else {
            client.refresh(config);
        }
        return client;
    }

    @Override
    public void deleteFileClient(Long configId) {
        clients.remove(configId);
    }

    private AbstractFileClient createFileClient(FileConfig config) {
        FileClient fileClient;
        if (config.getStorage().equals(FileStorage.LOCAL)) {
            return new LocalFileClient(config.getId(), config);
        }
        if (config.getStorage().equals(FileStorage.S3)) {
            return new S3FileClient(config.getId(), config);
        }
        throw new ServiceException("不支持的文件存储类型");
    }
}
